package com.ssy.lingxi.order.serviceimpl.mobile;

import cn.hutool.core.text.StrFormatter;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.querydsl.sql.SQLExpressions;
import com.ssy.lingxi.common.constant.order.OrderTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberAbilitySalesFeign;
import com.ssy.lingxi.member.merchant.api.feign.inner.MobileMemberSalesFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberSalesFindUserIdVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberSalesFeignPageQueryVO;
import com.ssy.lingxi.order.entity.OrderDO;
import com.ssy.lingxi.order.entity.QOrderDO;
import com.ssy.lingxi.order.model.bo.OrderPaymentBO;
import com.ssy.lingxi.order.model.bo.PayNodeBO;
import com.ssy.lingxi.order.model.bo.ProcessTaskBO;
import com.ssy.lingxi.order.model.bo.UpdateOrderProductPriceBO;
import com.ssy.lingxi.order.model.constant.*;
import com.ssy.lingxi.order.model.dto.MobileOrderPageDTO;
import com.ssy.lingxi.order.model.vo.basic.request.OrderAgreeVO;
import com.ssy.lingxi.order.model.vo.basic.request.OrderIdVO;
import com.ssy.lingxi.order.model.vo.mobile.request.MobileVendorOrderPageVO;
import com.ssy.lingxi.order.model.vo.mobile.request.MobileVendorUpdateFreightVO;
import com.ssy.lingxi.order.model.vo.mobile.request.MobileVendorValidateOrderPageVO;
import com.ssy.lingxi.order.model.vo.mobile.response.MobileVendorOrderDetailVO;
import com.ssy.lingxi.order.model.vo.mobile.response.MobileVendorOrderQueryVO;
import com.ssy.lingxi.order.model.vo.mobile.response.MobileVendorValidateSubscriptVO;
import com.ssy.lingxi.order.model.vo.vendor.request.VendorUpdatePayRateVO;
import com.ssy.lingxi.order.repository.OrderRepository;
import com.ssy.lingxi.order.service.base.*;
import com.ssy.lingxi.order.service.mobile.IMobileVendorOrderService;
import com.ssy.lingxi.order.utils.NumberUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * App - 业务员（销售）订单接口实现类
 * @author wyx
 * @version 2.0.0
 * @date 2022-03-22
 **/
@Service
public class MobileVendorOrderServiceImpl implements IMobileVendorOrderService {
    @Resource
    private IBaseCacheService baseCacheService;
    @Resource
    private IBaseMobileOrderService baseMobileOrderService;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private IBaseOrderProductService baseOrderProductService;
    @Resource
    private IBaseOrderPaymentService baseOrderPaymentService;
    @Resource
    private IBaseOrderHistoryService baseOrderHistoryService;
    @Resource
    private IBaseOrderService baseOrderService;
    @Resource
    private IBaseOrderTaskService baseOrderTaskService;
    @Resource
    private JPAQueryFactory jpaQueryFactory;
    @Resource
    private MobileMemberSalesFeign mobileMemberSalesFeign;
    @Resource
    private MemberAbilitySalesFeign memberAbilitySalesFeign;


    /**
     * 查看绑定订单 - 分页查询订单
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileVendorOrderQueryVO>> pageOrders(HttpHeaders headers, MobileVendorOrderPageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);

        Long memberId = null;
        List<Long> memberRoleIds;
        if (pageVO.getMemberId() == null && pageVO.getMemberRoleId() == null) {
            MemberSalesFindUserIdVO salesVO = new MemberSalesFindUserIdVO();
            salesVO.setMemberId(loginUser.getMemberId());
            salesVO.setMemberRoleId(loginUser.getMemberRoleId());
            salesVO.setUserId(loginUser.getUserId());

            //查询当前业务员绑定的所有下级会员
            Wrapper<List<Long>> resultVO = memberAbilitySalesFeign.roleIds();
            if (resultVO.getCode() != ResponseCode.SUCCESS.getCode()) {
                return Wrapper.fail(resultVO.getCode(), resultVO.getMessage());
            }
            memberRoleIds = resultVO.getData();
        } else {
            memberId = pageVO.getMemberId();
            memberRoleIds = Collections.singletonList(pageVO.getMemberRoleId());
        }

        MobileOrderPageDTO result = baseMobileOrderService.pageMobileVendorOrders(loginUser.getUserId(), memberId, memberRoleIds, pageVO.getMonth(), pageVO.getMemberName(), pageVO.getOrderType(), pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(order -> {
            MobileVendorOrderQueryVO queryVO = new MobileVendorOrderQueryVO(order);
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 查看绑定订单 - 订单详情
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MobileVendorOrderDetailVO> getOrderDetail(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        return baseMobileOrderService.getMobileVendorOrderDetail(idVO.getOrderId());
    }

    /**
     * 订单审核 - 订单数量角标
     * @param headers Http头部信息
     * @return 查询结果
     */
    @Override
    public Wrapper<List<MobileVendorValidateSubscriptVO>> getOrderSubscripts(HttpHeaders headers) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);

        MemberSalesFindUserIdVO salesVO = new MemberSalesFindUserIdVO();
        salesVO.setMemberId(loginUser.getMemberId());
        salesVO.setMemberRoleId(loginUser.getMemberRoleId());
        salesVO.setUserId(loginUser.getUserId());
        //查询当前业务员绑定的所有下级会员
        Wrapper<PageData<MemberSalesFeignPageQueryVO>> resultVO = mobileMemberSalesFeign.getSalesList(salesVO);
        if (resultVO.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(resultVO.getCode(), resultVO.getMessage());
        }
        List<Long> memberIds = resultVO.getData().getData().stream().map(MemberSalesFeignPageQueryVO::getMemberId).collect(Collectors.toList());
        List<Long> memberRoleIds = resultVO.getData().getData().stream().map(MemberSalesFeignPageQueryVO::getMemberRoleId).collect(Collectors.toList());

        QOrderDO qOrder = QOrderDO.orderDO;
        JPAQuery<MobileVendorValidateSubscriptVO> jpaQuery = jpaQueryFactory.select(Projections.constructor(MobileVendorValidateSubscriptVO.class, qOrder.vendorInnerStatus, SQLExpressions.count()))
                .from(qOrder)
                .where(qOrder.vendorUserId.eq(loginUser.getUserId()))
                .where(qOrder.buyerRoleId.in(memberRoleIds))
                .where(qOrder.vendorInnerStatus.in(VendorInnerStatusEnum.VENDOR_TO_SUBMIT_VALIDATE.getCode(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_ONE.getCode(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_TWO.getCode(), VendorInnerStatusEnum.VENDOR_TO_CONFIRM.getCode()))
                .where(qOrder.orderType.in(OrderTypeEnum.SPOT_PURCHASING.getCode(), OrderTypeEnum.INQUIRY_TO_PURCHASE.getCode(), OrderTypeEnum.CHANNEL_STRAIGHT_MINING.getCode(), OrderTypeEnum.CHANNEL_SPOT.getCode()))
                .groupBy(qOrder.vendorInnerStatus);
        return Wrapper.success(jpaQuery.fetch());
    }

    /**
     * 订单审核 - 分页查询列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileVendorOrderQueryVO>> pageValidateOrders(HttpHeaders headers, MobileVendorValidateOrderPageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);

        MemberSalesFindUserIdVO salesVO = new MemberSalesFindUserIdVO();
        salesVO.setMemberId(loginUser.getMemberId());
        salesVO.setMemberRoleId(loginUser.getMemberRoleId());
        salesVO.setUserId(loginUser.getUserId());
        //查询当前业务员绑定的所有下级会员
        Wrapper<PageData<MemberSalesFeignPageQueryVO>> resultVO = mobileMemberSalesFeign.getSalesList(salesVO);
        if (resultVO.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(resultVO.getCode(), resultVO.getMessage());
        }
        List<Long> memberIds = resultVO.getData().getData().stream().map(MemberSalesFeignPageQueryVO::getMemberId).collect(Collectors.toList());
        List<Long> memberRoleIds = resultVO.getData().getData().stream().map(MemberSalesFeignPageQueryVO::getMemberRoleId).collect(Collectors.toList());

        MobileOrderPageDTO result = baseMobileOrderService.pageMobileVendorValidateOrders(loginUser.getUserId(), memberIds, memberRoleIds, pageVO.getKeyword(), null, pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(MobileVendorOrderQueryVO::new).collect(Collectors.toList())));
    }

    /**
     * “待提交审核订单” - 查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileVendorOrderQueryVO>> pageSubmitToConfirmOrders(HttpHeaders headers, MobileVendorValidateOrderPageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);

        MemberSalesFindUserIdVO salesVO = new MemberSalesFindUserIdVO();
        salesVO.setMemberId(loginUser.getMemberId());
        salesVO.setMemberRoleId(loginUser.getMemberRoleId());
        salesVO.setUserId(loginUser.getUserId());
        //查询当前业务员绑定的所有下级会员
        Wrapper<PageData<MemberSalesFeignPageQueryVO>> resultVO = mobileMemberSalesFeign.getSalesList(salesVO);
        if (resultVO.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(resultVO.getCode(), resultVO.getMessage());
        }
        List<Long> memberIds = resultVO.getData().getData().stream().map(MemberSalesFeignPageQueryVO::getMemberId).collect(Collectors.toList());
        List<Long> memberRoleIds = resultVO.getData().getData().stream().map(MemberSalesFeignPageQueryVO::getMemberRoleId).collect(Collectors.toList());

        MobileOrderPageDTO result = baseMobileOrderService.pageMobileVendorValidateOrders(loginUser.getUserId(), memberIds, memberRoleIds, pageVO.getKeyword(), VendorInnerStatusEnum.VENDOR_TO_SUBMIT_VALIDATE.getCode(), pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(order -> {
            MobileVendorOrderQueryVO queryVO = new MobileVendorOrderQueryVO(order);
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “分页查询订单列表、待提交审核订单” - 修改运费和商品价格
     * @param headers   Http头部信息
     * @param freightVO 接口参数
     * @return 查询结果
     */
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Wrapper<Void> updateFreightAndProductPrices(HttpHeaders headers, MobileVendorUpdateFreightVO freightVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        OrderDO order = orderRepository.findById(freightVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 判断条件
        //只有“待提交审核订单”，才能修改运费与到手价
        if (!order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_TO_SUBMIT_VALIDATE.getCode())) {
            return Wrapper.fail(ResponseCode.ORDER_STATUS_IS_NOT_MATCHED);
        }

        //如果已经支付过，不能修改
        if (order.getHasPaid()) {
            return Wrapper.fail(ResponseCode.ORDER_CAN_NOT_UPDATE_FREIGHT_WHEN_HAS_PAID);
        }

        //Step 2: 修改订单商品到手价、金额
        if (!CollectionUtils.isEmpty(freightVO.getPrices())) {
            Wrapper<UpdateOrderProductPriceBO> productUpdateResult = baseOrderProductService.vendorUpdateProductPrices(order, freightVO.getPrices());
            if (productUpdateResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Wrapper.fail(productUpdateResult.getCode(), productUpdateResult.getMessage());
            }
            //保存修改商品单价外部订单流转记录
            productUpdateResult.getData().getRemarks().forEach(remark -> baseOrderHistoryService.saveVendorOrderOuterHistory(order.getId(), order.getOrderNo(), order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorMemberName(), loginUser.getMemberRoleName(), OrderOperationEnum.MODIFY_UINT_PRICE, order.getOuterStatus(), OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()), remark));

            order.setProductAmount(productUpdateResult.getData().getTotalAmount());
        }

        //Step 3: 修改运费
        if (NumberUtil.notNullAndPositiveZero(freightVO.getFreight())) {
            //修改前运费+修改后运费+修改原因
            String remark = StrFormatter.format(OrderStringEnum.REMARK_FORMAT1.getName(), NumberUtil.formatAmount(order.getFreight()), NumberUtil.formatAmount(freightVO.getFreight()), freightVO.getReason());
            //保存修改运费外部订单流转记录
            baseOrderHistoryService.saveVendorOrderOuterHistory(order.getId(), order.getOrderNo(), order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorMemberName(), loginUser.getMemberRoleName(), OrderOperationEnum.MODIFY_FREIGHT, order.getOuterStatus(), OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()), remark);

            order.setFreight(freightVO.getFreight());
        }

        //Step 4: 修改订单总额
        order.setTotalAmount(order.getProductAmount().add(order.getFreight()).subtract(order.getPromotionAmount()).subtract(order.getCouponAmount()).subtract(order.getDeductionAmount()).setScale(2, RoundingMode.HALF_UP));

        //Step 5: 修改支付记录中的支付金额
        Wrapper<Void> paymentUpdateResult = baseOrderPaymentService.vendorUpdatePaymentRate(order);
        if (paymentUpdateResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Wrapper.fail(paymentUpdateResult.getCode(), paymentUpdateResult.getMessage());

        }

        orderRepository.saveAndFlush(order);
        return Wrapper.success();
    }

    /**
     * “待提交审核订单” - 修改支付比例
     * @param headers   Http头部信息
     * @param payRateVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> updatePayRate(HttpHeaders headers, VendorUpdatePayRateVO payRateVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        OrderDO order = orderRepository.findById(payRateVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 判断条件
        //只有“待提交审核订单”，才能修改运费与到手价
        if (!order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_TO_SUBMIT_VALIDATE.getCode())) {
            Wrapper.fail(ResponseCode.ORDER_STATUS_IS_NOT_MATCHED);
        }

        //如果已经支付过，不能修改
        if (order.getHasPaid()) {
            return Wrapper.fail(ResponseCode.ORDER_CAN_NOT_UPDATE_PAY_RATE_WHEN_HAS_PAID);
        }

        //Step 2: 修改支付比例设置
        List<PayNodeBO> payNodes = payRateVO.getPayRates().stream().map(p -> new PayNodeBO(0, p.getBatchNo(), "", p.getPayRate().divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP))).collect(Collectors.toList());
        return baseOrderPaymentService.vendorUpdatePaymentRate(order, payNodes);
    }

    /**
     * “待审核订单（一级）” - 查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileVendorOrderQueryVO>> pageToValidateGradeOneOrders(HttpHeaders headers, MobileVendorValidateOrderPageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);

        MemberSalesFindUserIdVO salesVO = new MemberSalesFindUserIdVO();
        salesVO.setMemberId(loginUser.getMemberId());
        salesVO.setMemberRoleId(loginUser.getMemberRoleId());
        salesVO.setUserId(loginUser.getUserId());
        //查询当前业务员绑定的所有下级会员
        Wrapper<PageData<MemberSalesFeignPageQueryVO>> resultVO = mobileMemberSalesFeign.getSalesList(salesVO);
        if (resultVO.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(resultVO.getCode(), resultVO.getMessage());
        }
        List<Long> memberIds = resultVO.getData().getData().stream().map(MemberSalesFeignPageQueryVO::getMemberId).collect(Collectors.toList());
        List<Long> memberRoleIds = resultVO.getData().getData().stream().map(MemberSalesFeignPageQueryVO::getMemberRoleId).collect(Collectors.toList());

        MobileOrderPageDTO result = baseMobileOrderService.pageMobileVendorValidateOrders(loginUser.getUserId(), memberIds, memberRoleIds, pageVO.getKeyword(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_ONE.getCode(), pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(order -> {
            MobileVendorOrderQueryVO queryVO = new MobileVendorOrderQueryVO(order);
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待提交审核订单” - 提交审核
     * @param headers Http头部信息
     * @param agreeVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> submitToConfirmOrder(HttpHeaders headers, OrderAgreeVO agreeVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        OrderDO order = orderRepository.findById(agreeVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_TO_SUBMIT_VALIDATE.getCode()) || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 参数判断
        if (agreeVO.getAgree().equals(OrderServiceContants.DISAGREE) && !StringUtils.hasLength(agreeVO.getReason())) {
            return Wrapper.fail(ResponseCode.ORDER_VALIDATE_REASON_CAN_NOT_BE_EMPTY);
        }

        //记录上一次的供应商状态，用于发送报表数据
        int lastVendorInnerStatus = order.getVendorInnerStatus();

        //Step 2: 执行工作流任务（修改订单状态、记录内外流转记录）
        Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order, agreeVO.getAgree());
        if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        //Step 3: 如果是拼团订单，向营销服务发送拼团数据，等待拼团结果通知
        baseOrderService.notifyGroupOrder(order);

        orderRepository.saveAndFlush(order);

        //Step 4: 向报表服务发送统计数据
        baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), lastVendorInnerStatus, order.getVendorInnerStatus());

        //Step 5: 向消息服务发送供应购商实时消息
        baseOrderService.messageVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorUserId(), order.getVendorInnerStatus(), order.getOrderNo(), order.getDigest());

        //Step 6: 订单内部流转记录
        baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), OrderOperationEnum.SUBMIT_VALIDATE, order.getVendorInnerStatus(), StringUtils.hasLength(agreeVO.getReason()) ? agreeVO.getReason() : "");

        return Wrapper.success();
    }

    /**
     * “待审核订单（一级）” - 提交审核
     * @param headers Http头部信息
     * @param agreeVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> validateOrderGradeOne(HttpHeaders headers, OrderAgreeVO agreeVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        OrderDO order = orderRepository.findById(agreeVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_ONE.getCode()) || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 参数判断
        if (agreeVO.getAgree().equals(OrderServiceContants.DISAGREE) && !StringUtils.hasLength(agreeVO.getReason())) {
            return Wrapper.fail(ResponseCode.ORDER_VALIDATE_REASON_CAN_NOT_BE_EMPTY);
        }

        //记录上一次的供应商状态，用于发送报表数据
        int lastVendorInnerStatus = order.getVendorInnerStatus();

        //Step 2: 执行工作流任务（修改订单状态、记录内外流转记录）
        Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order, agreeVO.getAgree());
        if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        orderRepository.saveAndFlush(order);

        //Step 3: 向报表服务发送统计数据
        baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), lastVendorInnerStatus, order.getVendorInnerStatus());

        //Step 4: 向消息服务发送供应购商实时消息
        baseOrderService.messageVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorUserId(), order.getVendorInnerStatus(), order.getOrderNo(), order.getDigest());

        //Step 5: 订单内部流转记录
        baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), OrderOperationEnum.VALIDATE_GRADE_ONE, order.getVendorInnerStatus(), StringUtils.hasLength(agreeVO.getReason()) ? agreeVO.getReason() : "");

        return Wrapper.success();
    }

    /**
     * “待审核订单（二级）” - 查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileVendorOrderQueryVO>> pageToValidateGradeTwoOrders(HttpHeaders headers, MobileVendorValidateOrderPageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);

        MemberSalesFindUserIdVO salesVO = new MemberSalesFindUserIdVO();
        salesVO.setMemberId(loginUser.getMemberId());
        salesVO.setMemberRoleId(loginUser.getMemberRoleId());
        salesVO.setUserId(loginUser.getUserId());
        //查询当前业务员绑定的所有下级会员
        Wrapper<PageData<MemberSalesFeignPageQueryVO>> resultVO = mobileMemberSalesFeign.getSalesList(salesVO);
        if (resultVO.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(resultVO.getCode(), resultVO.getMessage());
        }
        List<Long> memberIds = resultVO.getData().getData().stream().map(MemberSalesFeignPageQueryVO::getMemberId).collect(Collectors.toList());
        List<Long> memberRoleIds = resultVO.getData().getData().stream().map(MemberSalesFeignPageQueryVO::getMemberRoleId).collect(Collectors.toList());

        MobileOrderPageDTO result = baseMobileOrderService.pageMobileVendorValidateOrders(loginUser.getUserId(), memberIds, memberRoleIds, pageVO.getKeyword(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_TWO.getCode(), pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(order -> {
            MobileVendorOrderQueryVO queryVO = new MobileVendorOrderQueryVO(order);
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待审核订单（二级）” - 提交审核
     * @param headers Http头部信息
     * @param agreeVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> validateOrderGradeTwo(HttpHeaders headers, OrderAgreeVO agreeVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        OrderDO order = orderRepository.findById(agreeVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_TWO.getCode()) || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 参数判断
        if (agreeVO.getAgree().equals(OrderServiceContants.DISAGREE) && !StringUtils.hasLength(agreeVO.getReason())) {
            return Wrapper.fail(ResponseCode.ORDER_VALIDATE_REASON_CAN_NOT_BE_EMPTY);
        }

        //记录上一次的供应商状态，用于发送报表数据
        int lastVendorInnerStatus = order.getVendorInnerStatus();

        //Step 2: 执行工作流任务（修改订单状态、记录内外流转记录）
        Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order, agreeVO.getAgree());
        if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        orderRepository.saveAndFlush(order);

        //Step 3: 向报表服务发送统计数据
        baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), lastVendorInnerStatus, order.getVendorInnerStatus());

        //Step 4: 向消息服务发送供应购商实时消息
        baseOrderService.messageVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorUserId(), order.getVendorInnerStatus(), order.getOrderNo(), order.getDigest());

        //Step 5: 订单内部流转记录
        baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), OrderOperationEnum.VALIDATE_GRADE_TWO, order.getVendorInnerStatus(), StringUtils.hasLength(agreeVO.getReason()) ? agreeVO.getReason() : "");

        return Wrapper.success();
    }

    /**
     * “待确认订单” - 查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileVendorOrderQueryVO>> pageToConfirmOrders(HttpHeaders headers, MobileVendorValidateOrderPageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);

        MemberSalesFindUserIdVO salesVO = new MemberSalesFindUserIdVO();
        salesVO.setMemberId(loginUser.getMemberId());
        salesVO.setMemberRoleId(loginUser.getMemberRoleId());
        salesVO.setUserId(loginUser.getUserId());
        //查询当前业务员绑定的所有下级会员
        Wrapper<PageData<MemberSalesFeignPageQueryVO>> resultVO = mobileMemberSalesFeign.getSalesList(salesVO);
        if (resultVO.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(resultVO.getCode(), resultVO.getMessage());
        }
        List<Long> memberIds = resultVO.getData().getData().stream().map(MemberSalesFeignPageQueryVO::getMemberId).collect(Collectors.toList());
        List<Long> memberRoleIds = resultVO.getData().getData().stream().map(MemberSalesFeignPageQueryVO::getMemberRoleId).collect(Collectors.toList());
//        List<Integer> vendorInnerStatuses = Stream.of(VendorInnerStatusEnum.VENDOR_SUBMIT_VALIDATE_NOT_PASSED.getCode(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_ONE_NOT_PASSED.getCode(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_TWO_NOT_PASSED.getCode(), VendorInnerStatusEnum.VENDOR_TO_CONFIRM.getCode()).collect(Collectors.toList());
        MobileOrderPageDTO result = baseMobileOrderService.pageMobileVendorValidateOrders(loginUser.getUserId(), memberIds, memberRoleIds, pageVO.getKeyword(), VendorInnerStatusEnum.VENDOR_TO_CONFIRM.getCode(), pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(result.getTotalCount(), result.getOrders().stream().map(order -> {
            MobileVendorOrderQueryVO queryVO = new MobileVendorOrderQueryVO(order);
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待确认订单” - 确认
     * @param headers Http头部信息
     * @param agreeVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> confirmOrder(HttpHeaders headers, OrderAgreeVO agreeVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromMobile(headers);
        List<Integer> vendorInnerStatuses = Stream.of(VendorInnerStatusEnum.VENDOR_SUBMIT_VALIDATE_NOT_PASSED.getCode(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_ONE_NOT_PASSED.getCode(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_TWO_NOT_PASSED.getCode(), VendorInnerStatusEnum.VENDOR_TO_CONFIRM.getCode()).collect(Collectors.toList());
        OrderDO order = orderRepository.findById(agreeVO.getOrderId()).orElse(null);
        if (order == null || !vendorInnerStatuses.contains(order.getVendorInnerStatus()) || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 参数判断
        if (agreeVO.getAgree().equals(OrderServiceContants.DISAGREE) && !StringUtils.hasLength(agreeVO.getReason())) {
            return Wrapper.fail(ResponseCode.ORDER_VALIDATE_REASON_CAN_NOT_BE_EMPTY);
        }

        //记录上一次的供应商状态，用于发送报表数据
        int lastVendorInnerStatus = order.getVendorInnerStatus();

        //Step 2: 执行工作流任务（修改订单状态、记录内外流转记录）
        Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order, agreeVO.getAgree());
        if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        //Step 3 : 确认订单之后有可能是支付环节，判断是否跳过支付环节
        if (agreeVO.getAgree().equals(OrderServiceContants.AGREE)) {
            Wrapper<OrderPaymentBO> jumpResult = baseOrderPaymentService.jumpOverOrderPaySerialTasks(order);
            if (jumpResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return Wrapper.fail(jumpResult.getCode(), jumpResult.getMessage());
            }
        }

        //Step 4: 如果是拼团订单，向营销服务发送拼团数据，等待拼团结果通知
        baseOrderService.notifyGroupOrder(order);

        orderRepository.saveAndFlush(order);

        //Step 5: 向报表服务发送统计数据
        baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), lastVendorInnerStatus, order.getVendorInnerStatus());
        baseOrderService.reportBuyerOrder(order.getBuyerMemberId(), order.getBuyerRoleId(), null, order.getBuyerInnerStatus());

        //Step 6: 向消息服务发送采购商、供应购商实时消息
        baseOrderService.messageVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorUserId(), order.getVendorInnerStatus(), order.getOrderNo(), order.getDigest());
        baseOrderService.messageBuyerOrder(order.getBuyerMemberId(), order.getBuyerRoleId(), order.getBuyerUserId(), order.getBuyerInnerStatus(), order.getOrderNo(), order.getDigest());

        //Step 7: 订单内、外流转记录
        baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), agreeVO.getAgree().equals(OrderServiceContants.AGREE) ? OrderOperationEnum.ACCEPT : OrderOperationEnum.REFUSE, order.getVendorInnerStatus(), StringUtils.hasLength(agreeVO.getReason()) ? agreeVO.getReason() : "");
        baseOrderHistoryService.saveVendorOrderOuterHistory(order.getId(), order.getOrderNo(), order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorMemberName(), loginUser.getMemberRoleName(), agreeVO.getAgree().equals(OrderServiceContants.AGREE) ? OrderOperationEnum.ACCEPT : OrderOperationEnum.REFUSE, order.getOuterStatus(), OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()), "");

        return Wrapper.success();
    }
}